package com.banksoft.cps.controller;



import com.banksoft.cps.bean.common.DataTip;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.util.DateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 */
@Controller
public class UploadImageController extends ControllerConstants {

    /**
     * 上传图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/kindUploadImage", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String uploadImage(HttpServletRequest request, HttpSession session, HttpServletResponse response, String dir) throws IOException {
        PrintWriter out = null;
        out = response.getWriter();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartFile file = ((DefaultMultipartHttpServletRequest) request).getFileMap().get("imgFile");
            String filePath = "";
            if("image".equals(dir)) {  //上传图片
                filePath = saveUploadImage(request.getSession().getServletContext(), file);
            } else if("file".equals(dir)) { //上传文件
                filePath = saveUploadFile(request.getSession().getServletContext(), file);
            } else if("flash".equals(dir)) {  //上传flash
                filePath = saveUploadFlash(request.getSession().getServletContext(), file);
            } else if("media".equals(dir)) {  //
                filePath = saveUploadMedia(request.getSession().getServletContext(), file);
            }
            map.put("error", 0);
            map.put("url", filePath);
        } catch (Exception e) {
            map.put("error", 1);
            if(e instanceof ServiceException) {
                map.put("message", ((ServiceException) e).getErrorTip().getMsg());
            } else {
                map.put("message", "上传失败");
            }
        }
        out.print(toJSONString(map));
        out.close();
        return null;
    }
    /**
     * �ϴ�ͼƬ������64λͼƬ����
     * @param image
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadImg",produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String uploadImg(String image, HttpServletRequest request) {
        if (null != image) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                //Base64����
                byte[] b = decoder.decodeBuffer(image);
                //����ͼƬ
                String fileName = System.currentTimeMillis() + ".jpeg";
                String path = "/upload/image/" + DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMdd");

                String targetPath = request.getSession().getServletContext().getRealPath(path);
                if(!new File(targetPath).exists()) {
                    new File(targetPath).mkdirs();
                }
                String imgFilePath = targetPath + File.separator + fileName;//�����ɵ�ͼƬ
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                path = path+File.separator + fileName;
                path = path.replaceAll("\\\\","/");
                DataTip tip = new DataTip(true, null, path);
                //tip.setData(uri + fileName);
                return toJSONString(tip);
            } catch (Exception e) {
                e.printStackTrace();
                return toJSONString(new DataTip(false, "上传过程中出错！" + e.getMessage(), null));
            }
        }
        return toJSONString(new DataTip(false, "上传过程中出错！", null));
    }

    /**
     * �ϴ�ͼƬ
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadImage", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String uploadImage(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        try {
            String filePath = saveUploadImage(request.getSession().getServletContext(), file);
            DataTip dataTip = new DataTip(true, "", filePath);
            return toJSONString(dataTip);
        } catch (Exception e) {
            return toExceptionString(e);
        }
    }

    /**
     * �ϴ��ļ�
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadFile", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String uploadFile(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        try {
            String filePath = saveUploadFile(request.getSession().getServletContext(), file);
            DataTip dataTip = new DataTip(true, "", filePath);
            return toJSONString(dataTip);
        } catch (Exception e) {
            return toExceptionString(e);
        }
    }


    @RequestMapping(value = "/uploadImagePl", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String uploadImagePl(@RequestParam(value = "file") MultipartFile file, HttpServletResponse response,
                                HttpServletRequest request) throws IOException {
        PrintWriter out = null;
        out = response.getWriter();
        try {
            String filePath = saveUploadImage(request.getSession().getServletContext(), file);
            out.print("FILEID:" + filePath);
        } catch (Exception e) {
           if(e instanceof ServiceException) {
               String message = ((ServiceException) e).getErrorTip().getMsg();
               out.print("ERROR:" + message);
           } else {
               out.print("false");
           }
        }
        out.close();
        return null;
    }
}
